package dialog;

import java.util.HashMap;
import java.util.Map;

import com.lanhai.utils.DialogUtils;
import com.lanhai.utils.HttpUtils;

import application.MainAction;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Stage;
import net.sf.json.JSONObject;
/**
 * 管理员登录窗口
 * @author liangmin
 *
 */
public class PassPanel {

//	private static final Logger logger = Logger.getLogger(PassPanel.class);
	@FXML
	private Button button_confirm;
	@FXML
	private TextField password;
	
	public void init(MainAction mainDeal, String type) {
		
		button_confirm.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				confirm(mainDeal, type);			
			}
		});
		
		password.setOnKeyPressed(new EventHandler<KeyEvent>() {
		    @Override
		    public void handle(KeyEvent keyEvent){
		        if(keyEvent.getCode() == KeyCode.ENTER){
		        	confirm(mainDeal, type);
		        }
		    }
		});
	}
	
	public void confirm(MainAction mainAction, String type){
		String pwd = password.getText();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("pwd", pwd);
		String url = "http://" + mainAction.main.serverUrl + "/login";
		JSONObject jo = HttpUtils.httpPost2Json(url, params);
		try{
			if(!jo.isEmpty()){
				boolean flag = jo.getBoolean("success");
				if(flag){
					if(type.equals("testing")){
						mainAction.testing();
					}else if(type.equals("setting")){
						mainAction.setting();
					}else if(type.equals("traffic")){
						mainAction.traffic();
					}
					Stage stage = (Stage) password.getScene().getWindow();//获取当前窗体
					stage.close();				
				}else{
					DialogUtils.show("密码错误!", "提示", mainAction.main.logo);
				}
			}else{
				DialogUtils.show("远程服务器登录失败!", "提示", mainAction.main.logo);
			}			
		}catch(Exception e){
			DialogUtils.show("远程服务器登录失败!", "提示", mainAction.main.logo);
			e.printStackTrace();
		}	
	}
	
}
